package com.example.agriapp;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.agriapp.data.AgriDatabaseHelper;

public class ProductProvider extends ContentProvider {
    // 数据库帮助类
    private AgriDatabaseHelper dbHelper;
    
    // 授权机构
    public static final String AUTHORITY = "com.example.agriapp.provider";
    
    // 基础URI
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    
    // 路径常量
    public static final String PATH_PRODUCTS = "products";
    
    // 完整URI
    public static final Uri CONTENT_URI = 
            BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRODUCTS).build();
    
    // URI匹配码
    private static final int PRODUCTS = 100;
    private static final int PRODUCT_ID = 101;
    
    private static final UriMatcher sUriMatcher = buildUriMatcher();
    
    private static UriMatcher buildUriMatcher() {
        UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
        
        // 匹配整个产品表
        matcher.addURI(AUTHORITY, PATH_PRODUCTS, PRODUCTS);
        
        // 匹配单个产品ID
        matcher.addURI(AUTHORITY, PATH_PRODUCTS + "/#", PRODUCT_ID);
        
        return matcher;
    }

    @Override
    public boolean onCreate() {
        dbHelper = new AgriDatabaseHelper(getContext());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
                        @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        final SQLiteDatabase db = dbHelper.getReadableDatabase();
        final int match = sUriMatcher.match(uri);
        Cursor retCursor;
        
        switch (match) {
            case PRODUCTS:
                retCursor = db.query(
                        AgriDatabaseHelper.TABLE_PRODUCTS,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                break;
            case PRODUCT_ID:
                String id = uri.getLastPathSegment();
                retCursor = db.query(
                        AgriDatabaseHelper.TABLE_PRODUCTS,
                        projection,
                        AgriDatabaseHelper.COLUMN_ID + " = ?",
                        new String[]{id},
                        null,
                        null,
                        sortOrder
                );
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        retCursor.setNotificationUri(getContext().getContentResolver(), uri);
        return retCursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        final int match = sUriMatcher.match(uri);
        
        switch (match) {
            case PRODUCTS:
                return "vnd.android.cursor.dir/" + AUTHORITY + "." + PATH_PRODUCTS;
            case PRODUCT_ID:
                return "vnd.android.cursor.item/" + AUTHORITY + "." + PATH_PRODUCTS;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        Uri returnUri;
        
        switch (match) {
            case PRODUCTS:
                long id = db.insert(AgriDatabaseHelper.TABLE_PRODUCTS, null, values);
                if (id > 0) {
                    returnUri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(id));
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        getContext().getContentResolver().notifyChange(uri, null);
        return returnUri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        int rowsDeleted;
        
        switch (match) {
            case PRODUCTS:
                rowsDeleted = db.delete(AgriDatabaseHelper.TABLE_PRODUCTS, selection, selectionArgs);
                break;
            case PRODUCT_ID:
                String id = uri.getLastPathSegment();
                rowsDeleted = db.delete(
                        AgriDatabaseHelper.TABLE_PRODUCTS,
                        AgriDatabaseHelper.COLUMN_ID + " = ?",
                        new String[]{id}
                );
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        if (rowsDeleted != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsDeleted;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
                      @Nullable String[] selectionArgs) {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        int rowsUpdated;
        
        switch (match) {
            case PRODUCTS:
                rowsUpdated = db.update(AgriDatabaseHelper.TABLE_PRODUCTS, values, selection, selectionArgs);
                break;
            case PRODUCT_ID:
                String id = uri.getLastPathSegment();
                rowsUpdated = db.update(
                        AgriDatabaseHelper.TABLE_PRODUCTS,
                        values,
                        AgriDatabaseHelper.COLUMN_ID + " = ?",
                        new String[]{id}
                );
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsUpdated;
    }
}